package com.java2104.controller;

import com.java2104.entity.User;
import org.springframework.stereotype.Controller;

import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.servlet.view.RedirectView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@Controller
@SessionAttributes(names = {"loginUser"}) //将属性的作用范围扩大到会话作用域
public class IndexController {


    @PostMapping("/login")
    @ResponseBody
    public Map asyncLogin(User user, Model model) {
        Map map = new HashMap();
        //约定用户名: xiaofeng 密码: 456789
        if ("xiaofeng".equals(user.getUsername()) && "456789".equals(user.getPassword())) {
            //登录成功，将登录用户的信息保存到会话中
//            session.setAttribute("loginUser", user);
            model.addAttribute("loginUser", user);

            map.put("status", "success");
            map.put("msg", "登陆成功！");
        } else {
            map.put("status", "fail");
            map.put("msg", "用户名或密码错误，请重试！");
        }
        return map;
    }

    //写一个测试方法，响应登录页面
    //ModelAndView是模型数据和逻辑视图的一个整体
    //页面跳转使用 @GetMapping
    //1.浏览器地址栏输入 2.点击超链接 3.提交表单get
    @GetMapping({"/login", "/login.jsp", "/login.html"})
    public ModelAndView login() {
        ModelAndView mv = new ModelAndView("login");//设置逻辑视图名
        mv.addObject("appName", "中软国际OA");
        return mv;
    }

    //执行具体的业务则用 @PostMapping
    //1.提交表单 post
    //@PostMapping(path = "/login", params = {"username=admin", "password=123456"})
    public String login(HttpSession session, User user) {
        //登录成功，将登录用户的信息保存到会话中
        session.setAttribute("loginUser", user);
        return "redirect:/home";
    }



    @RequestMapping("/logout")
    public View logout(HttpSession session, RedirectAttributes ra) {
        User loginUser = (User)session.getAttribute("loginUser");
        String username = loginUser.getUsername();//获取之前登陆的账号
//        model.addAttribute("username", username);//把用户名添加到Model属性中
//        model.addAttribute("password", loginUser.getPassword());
        session.invalidate();//销毁会话，其中保存的登录状态也随之消失

        ra.addAttribute("username", username);//添加一个普通属性
        ra.addFlashAttribute("password", loginUser.getPassword());//添加一个会话作用域的属性

        return new RedirectView("/login");
    }


    @RequestMapping("/home") //@RequestMapping(value = "/home") @RequestMapping(path = "/home")
    public String toHome(@CookieValue("JSESSIONID") String sessionId, Model model) {
        model.addAttribute("sessionId", sessionId);
        return "home";
    }

    //模拟登录页面的访问也写一个类似功能的方法
    @RequestMapping("/register")
    public ModelAndView register() {
        ModelAndView mv = new ModelAndView("register");
        return mv;
    }
    // 只接受get方式的请求 http://localhost:8080/hello?name=liudehua&station=China&job=程序员
    @RequestMapping(path = "/hello", method = RequestMethod.GET)
    @GetMapping(path = "/hello")
    //String类型的返回值只能表示逻辑视图名
    public String a(Model model,
                    @RequestParam("name") @ModelAttribute("name") String n,
                    @RequestParam("station") @ModelAttribute("station") String s,
                    @RequestParam("job") @ModelAttribute("job") String j) {
        model.addAttribute("list", new String[] {"Java", "Android", "C#"});
        //将请求的参数值一并加到响应资源的属性中
//        model.addAttribute("name", n);
//        model.addAttribute("station", s);
//        model.addAttribute("job", j);
        return "b";// /WEB-INF/jsp/b.jsp
    }

    // http://localhost:8080/hello2/zxy/England/docter
    @RequestMapping("/hello2/{name}/{station}/{job}")
    public String b(Model model, @PathVariable("name") String n, @PathVariable("station") String s,
                    @PathVariable("job") String j) {
        model.addAttribute("list", new String[] {"分布式", "物联网", "人工智能"});
        //将请求的参数值一并加到响应资源的属性中
        model.addAttribute("name", n);
        model.addAttribute("station", s);
        model.addAttribute("job", j);
        return "b";// /WEB-INF/jsp/b.jsp
    }

    @RequestMapping("/servlet")
    public String m1(HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        return null;
    }

    @RequestMapping("/curUser")
    @ResponseBody
    //@SessionAttribute("loginUser") 获取会话中的登录用户对象注入方法参数中
    public User returnLoginUser(@SessionAttribute("loginUser") User user) {
        user.setNickName("宋晓峰yyds");
        return user;
    }

    @RequestMapping("/testError")
    public String testError() {
        String str = null;
        System.out.println(str.length());//模拟程序出现空指针异常
        /*if (true)
            throw new RuntimeException("字符串长度超出限制！");*/
        return null;
    }

    /*@RequestMapping("/not_in_work_timing")
    public String notInWorkTiming() {
        return "notInWorkTime";
    }*/
}
